"""
检查查询对象的类型
"""

from app import create_app
from app.models import ActivationCode
from app import db


def debug_query_type():
    """检查查询对象的类型"""
    app = create_app()
    
    with app.app_context():
        try:
            print("=== 检查查询对象的类型 ===")
            
            # 检查ActivationCode.query的类型
            model_query = ActivationCode.query
            print(f"ActivationCode.query 类型: {type(model_query)}")
            print(f"ActivationCode.query 类名: {model_query.__class__.__name__}")
            
            # 检查db.session.query()的类型
            session_query = db.session.query(ActivationCode)
            print(f"db.session.query() 类型: {type(session_query)}")
            print(f"db.session.query() 类名: {session_query.__class__.__name__}")
            
            # 检查是否是同一个类型
            if type(model_query) == type(session_query):
                print("⚠️ 两种查询方式返回相同类型，都会应用我们的租户过滤机制")
            else:
                print("✅ 两种查询方式返回不同类型")
            
            # 测试原生SQL执行
            print("\n--- 测试原生SQL执行 ---")
            raw_sql = """
            SELECT * FROM activation_codes 
            WHERE tenant_id = 14 
            AND status = 0 
            AND usage_count = 3 
            AND is_copied = 0 
            AND is_exported = 0 
            AND created_by = 27 
            LIMIT 5
            """
            
            result = db.session.execute(raw_sql)
            raw_codes = result.fetchall()
            print(f"原生SQL查询结果: {len(raw_codes)} 条记录")
            
            if len(raw_codes) > 0:
                print("✅ 原生SQL有结果，说明数据存在")
                print("❌ 问题确实在于我们的查询机制")
            else:
                print("❌ 原生SQL也没结果，可能是数据问题")
            
            return True
            
        except Exception as e:
            print(f"❌ 检查失败: {str(e)}")
            import traceback
            traceback.print_exc()
            return False


if __name__ == "__main__":
    debug_query_type()
